package com.colin.juc.atomic;

import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.stream.IntStream;

/**
 * Created by Colin on 2020/4/19 19:22
 * email: colinzhaodong@gmail.com
 * desc: 演示Accumulator累加器的使用
 *
 * @author zhaod
 */
public class LongAccumulatorDemo {
	public static void main(String[] args) {
		LongAccumulator longAccumulator = new LongAccumulator(Long::sum, 0);
		ExecutorService service = new ThreadPoolExecutor(20, 20, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), r -> new Thread(r, "colin-thread"));
		IntStream.range(1,10000000).forEach(i->service.execute(() -> longAccumulator.accumulate(i)));
		service.shutdown();
		try {
			if (!service.awaitTermination(1,TimeUnit.MILLISECONDS)){
				service.shutdownNow();
			}
		} catch (InterruptedException e) {
			service.shutdownNow();
			Thread.currentThread().interrupt();
		}
		System.out.println(service.isTerminated());
		System.out.println(longAccumulator.getThenReset());
	}
}
